package com.ad.pet.app.serach;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.githang.statusbar.StatusBarCompat;
import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.MainActivity;
import com.ad.pet.R;
import com.ad.pet.app.main.adapter.HomeIndexMallAdapter;
import com.ad.pet.app.serach.adapter.SearchFilterAdapter;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.BaseActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.KeyWord;
import com.ad.pet.models.remote.home.HomeMall;
import com.ad.pet.models.remote.mall.FilterAttr;
import com.ad.pet.models.remote.mall.SearchEndGood;
import com.ad.pet.ui.SimpleDividerDecoration;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by SEELE on 2018/3/28.
 */

public class SerachEndActivity extends BaseActivity implements SerachHistoryContract.View {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    EditText mTvTitle;
    @BindView(R.id.container)
    LinearLayout mContainer;
    @BindView(R.id.iv_search)
    ImageView mIvSearch;
    @BindView(R.id.tv_default)
    TextView mTvDefault;
    @BindView(R.id.tv_sales)
    TextView mTvSales;
    @BindView(R.id.linear_price)
    LinearLayout mLinearPrice;
    @BindView(R.id.ic_chose)
    TextView mIcChose;
    @BindView(R.id.linear_select)
    LinearLayout mLinearSelect;
    @BindView(R.id.recycler_good)
    RecyclerView mRecyclerGood;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout mSwipeRefresh;
    @BindView(R.id.et_min)
    EditText mEtMin;
    @BindView(R.id.et_max)
    EditText mEtMax;
    @BindView(R.id.tv_confirm)
    TextView mTvConfirm;
    @BindView(R.id.layout_filter)
    RelativeLayout mLayoutFilter;
    @BindView(R.id.iv_change)
    ImageView ivChange;
    @BindView(R.id.recycler_filter)
    RecyclerView recyclerFilter;
    @BindView(R.id.tv_chose_cancel)
    TextView tvChoseCancel;
    private String mKeyword;

    @BindView(R.id.nice_spinner)
    NiceSpinner mNiceSpinner;

    @BindView(R.id.tv_canback2)
    TextView mTvCanBack2;

    @BindView(R.id.tv_can_get_back)
    TextView mTvCanGetBack;

    @BindView(R.id.linear_pop)
    LinearLayout mLinearPop;

    @BindView(R.id.linear_cat_tips)
    LinearLayout mLinearCatTips;

    @BindView(R.id.relative_tips)
    RelativeLayout mRelativeTips;

    boolean isShowTips = true;


    @Inject
    SerachHistoryPresenter mSerachHistoryPresenter;

    int mPage = 1;
    int mPageSize = 10;
    String mSort = "";
    String mSortOrder = "";
    String mStartPrice = "0";
    String mEndPrice = "99999";
    private String mCategoryId;
    private String mIsSearchKey = "";
    private HomeIndexMallAdapter mHomeIndexMallAdapter;

    //    @BindView(R.id.tv_reset)
//    TextView mTvReset;
    private List<String> mDataset;

    @BindView(R.id.relative_change)
    RelativeLayout mRelativeLayoutChange;


    boolean isListView = true;
    private SimpleDividerDecoration mSimpleDividerDecoration;
    private SearchFilterAdapter searchFilterAdapter;
    private int floatCat;


    @Override
    protected void initViews() {
        mKeyword = getIntent().getStringExtra("keyword");
        mKeyword = TextUtils.isEmpty(mKeyword) ? "" : mKeyword;
        mCategoryId = getIntent().getStringExtra(Constant.CATEGROY_ID);
        mCategoryId = TextUtils.isEmpty(mCategoryId) ? "" : mCategoryId;
//        mIsSearchKey = getIntent().getStringExtra(Constant.IS_MAIN);
//        mIsSearchKey = TextUtils.isEmpty(mIsSearchKey) ? "" : mIsSearchKey;
        mTvTitle.setText(mKeyword);
        mSerachHistoryPresenter.onCreate(this);

        mRecyclerGood.setLayoutManager(new GridLayoutManager(mActivity, 2));
        mHomeIndexMallAdapter = new HomeIndexMallAdapter(null);
        mRecyclerGood.setAdapter(mHomeIndexMallAdapter);
        mSimpleDividerDecoration = new SimpleDividerDecoration(mActivity, 2, R.color.graycf);

        recyclerFilter.setLayoutManager(new LinearLayoutManager(mActivity));
        searchFilterAdapter = new SearchFilterAdapter(null);
        recyclerFilter.setAdapter(searchFilterAdapter);

        mLayoutFilter.setVisibility(View.GONE);
        if (TextUtils.isEmpty(mTvTitle.getText().toString())){
            mTvTitle.setText("全球包邮");
        }
    }

    @Override
    protected void initData() {
        mDataset = new LinkedList<>(Arrays.asList(getString(R.string.price), getString(R.string.price_up), getString(R.string.price_down)));
        mNiceSpinner.attachDataSource(mDataset);
        mSerachHistoryPresenter.getSearchEnd(mKeyword, String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);


    }

    @Override
    protected void initEvents() {
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mTvTitle.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (TextUtils.isEmpty(mTvTitle.getText().toString().trim())) {
                    ToastUtil.getToastUtil().showShort(getString(R.string.please_input_serach_content));
                    return false;
                }
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mKeyword = mTvTitle.getText().toString().trim();
                    mSort = "";
                    mSortOrder = "";
                    mStartPrice = "0";
                    mEndPrice = "99999";
                    mPage = 1;
                    mCategoryId = "";
                    mSerachHistoryPresenter.getSearchEnd(mTvTitle.getText().toString(), String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);

                    return true;
                }
                return false;
            }
        });
        mIvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mTvTitle.getText().toString().trim())) {
                    ToastUtil.getToastUtil().showShort(getString(R.string.please_input_serach_content));
                    return;
                }
                mSort = "";
                mSortOrder = "";
                mStartPrice = "0";
                mEndPrice = "99999";
                mPage = 1;
                mKeyword = mTvTitle.getText().toString().trim();
                mCategoryId = "";
                mSerachHistoryPresenter.getSearchEnd(mTvTitle.getText().toString(), String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);


            }
        });
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPage = 1;
                mSerachHistoryPresenter.getSearchEnd(mKeyword, String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);
                mHomeIndexMallAdapter.setEnableLoadMore(false);
            }
        });
        mHomeIndexMallAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPage++;
                mSerachHistoryPresenter.getSearchEnd(mKeyword, String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);
            }
        }, mRecyclerGood);

        mLinearSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLayoutFilter.getVisibility() == View.VISIBLE) {
                    mLayoutFilter.setVisibility(View.GONE);
                } else {
                    mLayoutFilter.setVisibility(View.VISIBLE);
                }
            }
        });

//        mTvReset.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mEtMax.setText("");
//                mEtMin.setText("");
//            }
//        });
        tvChoseCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLayoutFilter.setVisibility(View.GONE);
            }
        });
        mTvDefault.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSort = "";
                mSortOrder = "";
                mStartPrice = "0";
                mEndPrice = "99999";
                mPage = 1;
                mSerachHistoryPresenter.getSearchEnd(mKeyword, String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);

            }
        });


        mTvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(mEtMin.getText().toString())) {
                    mStartPrice = "";
                } else {
                    mStartPrice = mEtMin.getText().toString();
                }
                if (TextUtils.isEmpty(mEtMax.getText().toString())) {
                    mEndPrice = "";
                } else {
                    mEndPrice = mEtMax.getText().toString();

                }

                String selectAttr = "";
                List<FilterAttr> filterAttrs = searchFilterAdapter.getData();
                for (int i = 0; i < filterAttrs.size(); i++) {
                    for (int j = 0; j < filterAttrs.get(i).getAttr_value_list().size(); j++) {
                        if (filterAttrs.get(i).getAttr_value_list().get(j).getIs_selected() == 1) {
                            String attrid = filterAttrs.get(i).getAttr_id();
                            String valueId = filterAttrs.get(i).getAttr_value_list().get(j).getAttr_value_id();
                            String endId = attrid + ":" + valueId;
                            selectAttr = selectAttr + endId + ";";
                        }
                    }
                }
                if (!TextUtils.isEmpty(selectAttr)) {
                    selectAttr = selectAttr.substring(0, selectAttr.length() - 1);
                }
                mIsSearchKey = selectAttr;

                mPage = 1;
                mSerachHistoryPresenter.getSearchEnd(mKeyword, String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);
                mLayoutFilter.setVisibility(View.GONE);
            }
        });
        mTvSales.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSort = "sales";
                mPage = 1;
                mSerachHistoryPresenter.getSearchEnd(mKeyword, String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);
            }
        });

        mNiceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSort = "price";
//                if (position==0){
//
//                }
                if (position == 1) {
                    mSortOrder = "desc";
                }
                if (position == 2) {
                    mSortOrder = "asc";
                }
                mPage = 1;
                mSerachHistoryPresenter.getSearchEnd(mKeyword, String.valueOf(mPage), String.valueOf(mPageSize), mSort, mSortOrder, mStartPrice, mEndPrice, mCategoryId, mIsSearchKey);
            }
        });

        mRelativeLayoutChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isListView = !isListView;
                List<HomeMall> homeMalls = mHomeIndexMallAdapter.getData();
                for (int i = 0; i < homeMalls.size(); i++) {
                    homeMalls.get(i).setItemType(isListView ? 0 : 1);
                }
                if (isListView) {
                    mRecyclerGood.setLayoutManager(new GridLayoutManager(mActivity, 2));
                    mRecyclerGood.removeItemDecoration(mSimpleDividerDecoration);

                } else {
                    mRecyclerGood.setLayoutManager(new LinearLayoutManager(mActivity));
                    mRecyclerGood.addItemDecoration(mSimpleDividerDecoration);


                }
//                mHomeIndexMallAdapter.notifyDataSetChanged();
            }
        });
//      mNiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//          @Override
//          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                mSort = "price";
//                mSortOrder =
//          }
//
//          @Override
//          public void onNothingSelected(AdapterView<?> parent) {
//
//          }
//      });


        mRelativeTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowTips = !isShowTips;
                if (isShowTips) {
                    if (floatCat == 1) {
                        mLinearCatTips.setVisibility(View.VISIBLE);
                        mLinearPop.setVisibility(View.GONE);
                    } else if (floatCat == 1) {
                        mLinearPop.setVisibility(View.VISIBLE);
                        mLinearCatTips.setVisibility(View.GONE);
                    }

                } else {
                    mLinearCatTips.setVisibility(View.GONE);
                    mLinearPop.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_serach_ending;
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }


    @Override
    protected boolean isStatusBarTransparent() {
        return false;
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onPause() {

        super.onPause();
    }

    @Override
    public void onResume() {

        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {
            case MainActivity.REQUEST_GO_MALL:
                setResult(RESULT_OK, data);
                finish();
                break;

        }
    }

    @Override
    protected void setContentViewBefore() {
        super.setContentViewBefore();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StatusBarCompat.setStatusBarColor(this, Color.parseColor("#0F0F33"), false);
        }

    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void error(int code, String msg) {

        if (code == 402) {
            SearchEndGood searchEndGood = new SearchEndGood();
            searchEndGood.setProduct_list(new ArrayList<HomeMall>());
            getSearchEndSuccess(searchEndGood);
        }
    }

    @Override
    public void getKeywordSuccess(List<KeyWord> commList) {

    }

    boolean isAttr = true;

    @Override
    public void getSearchEndSuccess(SearchEndGood searchEndGood) {
        floatCat = searchEndGood.getFloat_cat();
        if (isAttr) {
            List<FilterAttr> filterAttrs = searchEndGood.getAttr_list();
            searchFilterAdapter.setNewData(filterAttrs);
            isAttr = false;
        }
        List<HomeMall> goods = searchEndGood.getProduct_list();
        if (goods == null) {
            goods = new ArrayList<>();
        }
        for (HomeMall h : goods
                ) {
            h.setItemType(isListView ? 0 : 1);
        }
        mSwipeRefresh.setRefreshing(false);
        if (mPage == 1) {

            mHomeIndexMallAdapter.setNewData(goods);

        } else {
            //上拉 成功获取更多数据
            mHomeIndexMallAdapter.addData(goods);
            mHomeIndexMallAdapter.loadMoreComplete();
        }

        if (goods.size() < mPageSize) {//CommonConstant.PAGE_COUNT
            //暂无更多数据
            mHomeIndexMallAdapter.loadMoreEnd();
        }

        if (goods.size() == 0 && mPage == 1) {
            mHomeIndexMallAdapter.setEmptyView(R.layout.layout_empty);
        }

        if (searchEndGood.getFloat_cat() == 1) {
            mLinearCatTips.setVisibility(View.VISIBLE);
            mLinearPop.setVisibility(View.GONE);
            mTvCanGetBack.setText(searchEndGood.getFloat_cat_price());
            mRelativeTips.setVisibility(View.VISIBLE);
        } else if (searchEndGood.getFloat_cat() == 2) {
            mLinearPop.setVisibility(View.VISIBLE);
            mLinearCatTips.setVisibility(View.GONE);
            mTvCanBack2.setText(searchEndGood.getFloat_cat_price());
            mRelativeTips.setVisibility(View.VISIBLE);
        } else {
            mRelativeTips.setVisibility(View.GONE);
        }
    }

    @Override
    public void getTypeWordSucceses(List<KeyWord> commList) {

    }

    @Override
    public void getCateGoryWord(List<KeyWord> list) {

    }


    @Override
    public void finish() {
        if (mLayoutFilter.getVisibility() == View.VISIBLE) {
            mLayoutFilter.setVisibility(View.GONE);
        } else {
            super.finish();
        }


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
